/**
 * 消息通知
 */
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

import { Button, Drawer, DrawerProps, Menu, Space } from 'antd';

import { socket, store } from '@/store';

import { NoticeReadStatus } from '@/enum/notice';
import {
  sysMessageRecordClear,
  sysMessageRecordMarkAllRead
} from '@/services/base/jichumokuaixiaoxijilujiekou';
import { Icon } from '@iconify/react';

import styles from './index.module.scss';
import List, { ListInstance } from './list';

export type NoticeProps = DrawerProps & {};

export type NoticeRef = {
  open: (data?: { onChange?: () => void }) => void;
};

const Notice = ({ ...rest }: NoticeProps, ref: React.Ref<NoticeRef>) => {
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<NoticeRef['open']>[0]>();
  const [selectedKey, setSelectedKey] = useState<NoticeReadStatus | ''>('');
  const listRef = useRef<ListInstance>(null);

  useImperativeHandle(ref, () => {
    return {
      open: (data) => {
        setOpen(true);
        setArgs(data);
      }
    };
  });

  useEffect(() => {
    const onMessage = () => {
      console.log('onMessage', listRef.current);
      listRef.current?.reload();
    };

    socket?.on('error_notification', onMessage);
    socket?.on('system_notification', onMessage);

    return () => {
      socket?.off('error_notification', onMessage);
      socket?.off('system_notification', onMessage);
    };
  }, []);

  const onClose = () => {
    setOpen(false);
  };

  // 清空所有消息
  const clearAll = () => {
    store.app?.modal.confirm({
      title: '确认清空所有消息？',
      content: '清空后将无法恢复，请谨慎操作！',
      onOk: async () => {
        await sysMessageRecordClear();
        store.getUnreadCount();
        listRef.current?.reload();
      }
    });
  };

  // 全部标记为已读
  const markAllRead = () => {
    store.app?.modal.confirm({
      title: '确认全部标记为已读？',
      content: '标记后将无法恢复，请谨慎操作！',
      onOk: async () => {
        await sysMessageRecordMarkAllRead();
        store.getUnreadCount();
        listRef.current?.reload();
      }
    });
  };

  return (
    <Drawer
      // title='通知'
      closable={false}
      width="50%"
      {...rest}
      open={open}
      onClose={onClose}
      rootClassName={styles['notice-root']}
    >
      <div className={styles['notice']}>
        <div className={styles['notice-left']}>
          <Menu
            selectedKeys={[selectedKey]}
            onSelect={(e) => {
              setSelectedKey(e.key as typeof selectedKey);
            }}
            mode="vertical"
            items={[
              { label: '全部', key: '', icon: <Icon icon="ri:notification-3-fill" /> },
              {
                label: '未读',
                key: NoticeReadStatus.未读,
                icon: <Icon icon="ri:volume-up-fill" />
              },
              { label: '已读', key: NoticeReadStatus.已读, icon: <Icon icon="ri:volume-up-fill" /> }
            ]}
            style={{
              border: 'none'
            }}
          />
        </div>
        <div className={styles['notice-content']}>
          <div className={styles['notice-content-header']}>
            <Space>
              <Button onClick={clearAll}>清空所有消息</Button>
              <Button onClick={markAllRead}>全部标记为已读</Button>
            </Space>
          </div>
          <List viewed={selectedKey || undefined} listRef={listRef} />
        </div>
      </div>
    </Drawer>
  );
};

export default forwardRef(Notice) as (
  props: NoticeProps & {
    ref?: React.Ref<NoticeRef>;
  }
) => React.ReactElement;
